import { defineStore } from 'pinia'
import { useRoute } from 'vue-router'
import { showLoadingToast } from 'vant'
import qs from 'qs'
import jsCookie from 'js-cookie'

import storage from '@/utils/storage'

import { getUserByCode } from '@/api/index'

import { getUrlParams, WEB_HREF } from '@/utils/index'
import { VantMessage } from '@/utils/vant-utils'

// 对于可能有多code的query的话
export const getBusiUriQuery = (url) => {
  url = decodeURIComponent(url)
  const params = getUrlParams(url)
  let busiUri = params.busiUri
  let code = ''
  if (params.code instanceof Array) {
    busiUri = busiUri + `&code=${params.code[0]}`
    code = params.code[params.code.length - 1]
  } else {
    code = params.code
  }
  return {
    busiUri,
    code
  }
}

export const getRedirectUrl = (busiUri = '/') => {
  // 开发和生产的路径不同
  const redirectUrl = `${WEB_HREF}/auth?busiUri=${WEB_HREF}${busiUri}`
  const query = {
    appid: window.env.VUE_APP_APPID,
    state: parseInt(new Date().getTime() / 1000),
    response_type: 'code',
    scope: window.env.VUE_APP_SCOPE,
    agentid: window.env.VUE_APP_AGENTID,
    redirect_uri: redirectUrl
  }
  return `${window.env.VUE_APP_SDT_URL}/connect/oauth2/authorize?${qs.stringify(
    query
  )}#wechat_redirect`
}

export const authLogin = (busiUri = '/', isRefresh = false) => {
  const authUrl = getRedirectUrl(busiUri)
  const totast = showLoadingToast({
    message: '登录中...',
    forbidClick: true,
    duration: 0
  })
  try {
    // 如果是重新登录，刷新退出
    // if (isRefresh) {
    //   history.back()
    // }
    location.href = authUrl
    totast.close()
  } catch (error) {
    totast.close()
  }
}

export const TOOKEN_KEY = `LOGIN_TOKEN_${window.env.VUE_APP_APPID}`
export const USERID_KEY = `USER_ID_${window.env.VUE_APP_APPID}`

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: '', // 用户token
    userId: '', // 用户信息
    loginUrl: '' // 登录的url
  }),
  actions: {
    // 获取token
    getTooken() {
      // FIXME: development为了本地开发
      // token
      this.token =
        process.env.NODE_ENV === 'development'
          ? 'development'
          : storage.get(TOOKEN_KEY)
      // userid
      this.userId =
        process.env.NODE_ENV === 'development'
          ? 'development'
          : storage.get(USERID_KEY)
      return this.token
    },
    // 清除掉cookie
    clearCookies(cb = null) {
      storage.remove(TOOKEN_KEY)
      storage.remove(USERID_KEY)
      this.userId = ''
      this.token = ''
      cb && cb()
    },
    // 设置token
    setTooken(token) {
      storage.save(TOOKEN_KEY, token)
      this.token = token
    },
    // 设置userid
    setUserId(userId) {
      storage.save(USERID_KEY, userId)
      this.userId = userId
    },
    // 退出登陆
    loginOut() {
      const nowHref = location.href.replace(WEB_HREF, '')
      this.clearCookies(() => {
        authLogin(nowHref, true)
      })
    },
    // 换取token
    async loginByCode(code, cb) {
      // TODO: 通过code登陆 换取token及用户信息
      try {
        const res = await getUserByCode(code)
        if (res.data) {
          const { token, user } = res.data
          this.setTooken(token)
          this.setUserId(user.userId)
          cb()
        } else {
          VantMessage.error('获取信息失败')
        }
      } catch (error) {
        VantMessage.error('登陆失败')
      }
    }
  }
})
